<?php

/**
 * Aurorum - Open source digital signage
 *
 * @link http://digitalsignage.tk
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 *
 * @category Aurorum
 * @package Aurorum
 */

/**
 * This class provides access to data layer.
 *
 * @package Aurorum
 * @subpackage Models
 */

class ADS_DeploymentModel extends ADS_DefaultModel {

    public function countDeployments() {
        return dibi::fetch('
          SELECT
            COUNT(*) as cnt
          FROM
            [:wp:ads_deployments]
          %if', (bool)$this->useFilter, 'WHERE %and', $this->filter
        )->cnt;
    }
    
    public function getDeployments() {
        return dibi::fetchAll('
          SELECT            
            *
          FROM
            [:wp:ads_deployments] AS t1
           %if', (bool)$this->useFilter, 'WHERE %and', $this->filter, '%end',
          '%if', (bool)$this->useOrderBy, 'ORDER BY %by', $this->orderBy, '%end',
          '%if', (bool)$this->useLimit, '%lmt %ofs', $this->limit, $this->offset
        );
    }
     
    public function getDeployment($deploymentId) {
        if(!is_int($deploymentId)){
            throw new InvalidArgumentException(sprintf('Wrong parameters for method %s.',__METHOD__));
        }
        return dibi::fetch('
          SELECT            
            *
          FROM
            [:wp:ads_deployments] AS t1
          WHERE
            deploymentId = %i
        ', $deploymentId);
    }
    
    public function getCurrentDeployment() {
        return dibi::fetch('
          SELECT            
            *
          FROM
            [:wp:ads_deployments] AS t1
          ORDER BY 
            deploymentId DESC
          LIMIT 1
        ');
    }
    
    public function addDeployment($deployment){
        if(!is_array($deployment)){
            throw new InvalidArgumentException(sprintf('Wrong parameters for method %.',__METHOD__));
        }
        dibi::query('INSERT INTO [:wp:ads_deployments]', $deployment);
    }
    
    public function editDeployment($deploymentId, $deployment){
        if(!is_array($deployment) || !is_int($deploymentId)){
            throw new InvalidArgumentException(sprintf('Wrong parameters for method %.',__METHOD__));
        }

        dibi::query('UPDATE [:wp:ads_deployments] SET', $deployment, 'WHERE deploymentId = %i', $deploymentId);
    }
    
    public function removeDeployment($deploymentId){
        if(!is_int($deploymentId)){
            throw new InvalidArgumentException(sprintf('Wrong parameters for method %.',__METHOD__));
        }
        $deployment = $this->getDeployment($deploymentId);
        //update positions
        dibi::query('DELETE FROM [:wp:ads_deployments] WHERE deploymentId = %i LIMIT 1', $deploymentId);
    }

}
